<template>
  <div class="admin-tickets">
    <div class="page-header">
      <h2>票务管理</h2>
      <div class="header-actions">
        <el-button 
          v-if="hasPermission('ticket_add')"
          type="primary" 
          @click="showAddDialog = true"
        >
          添加票务信息
        </el-button>
        
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索票号/观众姓名/手机"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.ticketType" placeholder="票种" clearable @change="handleSearch">
            <el-option label="标准票" value="standard" />
            <el-option label="VIP票" value="vip" />
            <el-option label="团体票" value="group" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
            <el-option label="有效" value="valid" />
            <el-option label="已使用" value="used" />
            <el-option label="已过期" value="expired" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.paymentStatus" placeholder="支付状态" clearable @change="handleSearch">
            <el-option label="未支付" value="unpaid" />
            <el-option label="已支付" value="paid" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 票务信息列表 -->
    <el-table :data="ticketList" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="ticketNo" label="票号" width="120" />
      <el-table-column prop="visitorName" label="观众姓名" width="120" />
      <el-table-column prop="visitorPhone" label="联系电话" width="120" />
      <el-table-column prop="ticketType" label="票种" width="100">
        <template #default="scope">
          <el-tag :type="getTicketTypeType(scope.row.ticketType)">
            {{ getTicketTypeText(scope.row.ticketType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="ticketDate" label="参观日期" width="120" />
      <el-table-column prop="quantity" label="票数" width="80" />
      <el-table-column prop="totalAmount" label="总金额" width="100">
        <template #default="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="100">
        <template #default="scope">
          <el-tag :type="getPaymentStatusType(scope.row.paymentStatus)">
            {{ getPaymentStatusText(scope.row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="票务状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="150" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button 
            v-if="hasPermission('ticket_edit')"
            size="small" 
            type="primary" 
            @click="editTicket(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            v-if="hasPermission('ticket_audit') && scope.row.status === 'valid'"
            size="small" 
            type="warning" 
            @click="auditTicket(scope.row)"
          >
            审核
          </el-button>
          <el-button 
            v-if="hasPermission('ticket_delete')"
            size="small" 
            type="danger" 
            @click="deleteTicket(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑票务信息对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingTicket ? '编辑票务信息' : '添加票务信息'"
      width="800px"
    >
      <el-form :model="ticketForm" :rules="ticketRules" ref="ticketFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="观众姓名" prop="visitorName">
              <el-input v-model="ticketForm.visitorName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="visitorPhone">
              <el-input v-model="ticketForm.visitorPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="visitorEmail">
              <el-input v-model="ticketForm.visitorEmail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="票种" prop="ticketType">
              <el-select v-model="ticketForm.ticketType" placeholder="选择票种" style="width: 100%">
                <el-option label="标准票" value="standard" />
                <el-option label="VIP票" value="vip" />
                <el-option label="团体票" value="group" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="参观日期" prop="ticketDate">
              <el-date-picker
                v-model="ticketForm.ticketDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="票数" prop="quantity">
              <el-input-number v-model="ticketForm.quantity" :min="1" :max="10" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="票价" prop="price">
              <el-input-number v-model="ticketForm.price" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input-number v-model="ticketForm.totalAmount" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付状态" prop="paymentStatus">
              <el-select v-model="ticketForm.paymentStatus" placeholder="选择状态" style="width: 100%">
                <el-option label="未支付" value="unpaid" />
                <el-option label="已支付" value="paid" />
                <el-option label="已退款" value="refunded" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-select v-model="ticketForm.source" placeholder="选择来源" style="width: 100%">
                <el-option label="线上" value="online" />
                <el-option label="线下" value="offline" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveTicket" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="showAuditDialog"
      title="审核票务信息"
      width="500px"
    >
      <el-form :model="auditForm" ref="auditFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="valid">有效</el-radio>
            <el-radio label="cancelled">取消</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="auditForm.auditComment" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAuditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="auditing">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ticketApi } from '@/api/admin'

export default {
  name: 'AdminTickets',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const auditing = ref(false)
    const showAddDialog = ref(false)
    const showAuditDialog = ref(false)
    const editingTicket = ref(null)
    const auditingTicket = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      ticketType: '',
      status: '',
      paymentStatus: ''
    })
    
    // 票务信息表单
    const ticketForm = reactive({
      visitorName: '',
      visitorPhone: '',
      visitorEmail: '',
      ticketType: 'standard',
      ticketDate: '',
      quantity: 1,
      price: 0,
      totalAmount: 0,
      paymentStatus: 'unpaid',
      source: 'online'
    })
    
    // 审核表单
    const auditForm = reactive({
      status: 'valid',
      auditComment: ''
    })
    
    // 监听票数和票价变化，自动计算总金额
    watch([() => ticketForm.quantity, () => ticketForm.price], ([quantity, price]) => {
      ticketForm.totalAmount = (quantity || 0) * (price || 0)
    })
    
    // 表单验证规则
    const ticketRules = {
      visitorName: [
        { required: true, message: '请输入观众姓名', trigger: 'blur' }
      ],
      visitorPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ],
      visitorEmail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      ticketType: [
        { required: true, message: '请选择票种', trigger: 'change' }
      ],
      ticketDate: [
        { required: true, message: '请选择参观日期', trigger: 'change' }
      ]
    }
    
    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })
    
    // 票务信息列表
    const ticketList = ref([])
    
    // 权限检查
    const hasPermission = (permission) => {
      const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
      // 开发阶段先返回true，确保所有功能可见
      if (userInfo.permissions?.includes('all') || userInfo.userType === 'admin') return true
      return userInfo.permissions?.includes(permission) || true // 临时返回true用于测试
    }
    
    // 获取票种样式
    const getTicketTypeType = (type) => {
      const types = {
        standard: 'info',
        vip: 'warning',
        group: 'success'
      }
      return types[type] || 'info'
    }
    
    // 获取票种文本
    const getTicketTypeText = (type) => {
      const texts = {
        standard: '标准票',
        vip: 'VIP票',
        group: '团体票'
      }
      return texts[type] || '未知'
    }
    
    // 获取支付状态样式
    const getPaymentStatusType = (status) => {
      const types = {
        unpaid: 'danger',
        paid: 'success',
        refunded: 'warning'
      }
      return types[status] || 'info'
    }
    
    // 获取支付状态文本
    const getPaymentStatusText = (status) => {
      const texts = {
        unpaid: '未支付',
        paid: '已支付',
        refunded: '已退款'
      }
      return texts[status] || '未知'
    }
    
    // 获取状态样式
    const getStatusType = (status) => {
      const types = {
        valid: 'success',
        used: 'info',
        expired: 'warning',
        cancelled: 'danger'
      }
      return types[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        valid: '有效',
        used: '已使用',
        expired: '已过期',
        cancelled: '已取消'
      }
      return texts[status] || '未知'
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadTickets()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        keyword: '',
        ticketType: '',
        status: '',
        paymentStatus: ''
      })
      handleSearch()
    }
    
    // 加载票务信息数据
    const loadTickets = async () => {
      loading.value = true
      try {
        const params = {
          current: pagination.current,
          size: pagination.size,
          keyword: searchForm.keyword,
          ticketType: searchForm.ticketType,
          status: searchForm.status,
          paymentStatus: searchForm.paymentStatus
        }
        
        const response = await ticketApi.getTicketPage(params)
        if (response && response.data) {
          ticketList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('加载票务信息数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    
    // 编辑票务信息
    const editTicket = (ticket) => {
      editingTicket.value = ticket
      Object.assign(ticketForm, ticket)
      showAddDialog.value = true
    }
    
    // 删除票务信息
    const deleteTicket = async (ticket) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除票号 "${ticket.ticketNo}" 的票务信息吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await ticketApi.deleteTicket(ticket.id)
        ElMessage.success('删除成功')
        loadTickets()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 审核票务信息
    const auditTicket = (ticket) => {
      auditingTicket.value = ticket
      auditForm.status = 'valid'
      auditForm.auditComment = ''
      showAuditDialog.value = true
    }
    
    // 提交审核
    const submitAudit = async () => {
      auditing.value = true
      try {
        const userInfo = JSON.parse(localStorage.getItem('adminUser') || '{}')
        const params = {
          id: auditingTicket.value.id,
          status: auditForm.status,
          auditComment: auditForm.auditComment,
          auditUser: userInfo.userCode || 'admin'
        }
        
        await ticketApi.auditTicketWithParams(params)
        ElMessage.success('审核成功')
        showAuditDialog.value = false
        auditingTicket.value = null
        loadTickets()
      } catch (error) {
        ElMessage.error('审核失败')
      } finally {
        auditing.value = false
      }
    }
    
    // 保存票务信息
    const saveTicket = async () => {
      saving.value = true
      
      try {
        if (editingTicket.value) {
          await ticketApi.updateTicket({ ...ticketForm, id: editingTicket.value.id })
          ElMessage.success('票务信息更新成功')
        } else {
          await ticketApi.addTicket(ticketForm)
          ElMessage.success('票务信息添加成功')
        }
        
        showAddDialog.value = false
        editingTicket.value = null
        resetForm()
        loadTickets()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(ticketForm, {
        visitorName: '',
        visitorPhone: '',
        visitorEmail: '',
        ticketType: 'standard',
        ticketDate: '',
        quantity: 1,
        price: 0,
        totalAmount: 0,
        paymentStatus: 'unpaid',
        source: 'online'
      })
    }
    
    // 取消编辑
    const cancelEdit = () => {
      showAddDialog.value = false
      editingTicket.value = null
      resetForm()
    }
    
    
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadTickets()
    }
    
    const handleCurrentChange = (current) => {
      pagination.current = current
      loadTickets()
    }
    
    onMounted(() => {
      loadTickets()
    })
    
    return {
      loading,
      saving,
      auditing,
      showAddDialog,
      showAuditDialog,
      editingTicket,
      auditingTicket,
      searchForm,
      ticketForm,
      auditForm,
      ticketRules,
      pagination,
      ticketList,
      hasPermission,
      getTicketTypeType,
      getTicketTypeText,
      getPaymentStatusType,
      getPaymentStatusText,
      getStatusType,
      getStatusText,
      handleSearch,
      resetSearch,
      editTicket,
      deleteTicket,
      auditTicket,
      submitAudit,
      saveTicket,
      cancelEdit,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.admin-tickets {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>